package cn.sinata.wanglin.property.activity;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.xilada.xldutils.activitys.BaseActivity;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.view.SwipeRefreshRecyclerLayout;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sinata.wanglin.MyApplication;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.adapter.VillageAdapter;
import cn.sinata.wanglin.database.CityDao;
import cn.sinata.wanglin.database.CityInfo;
import cn.sinata.wanglin.database.JavaListBeanCallBack;
import cn.sinata.wanglin.database.ProvinceDao;
import cn.sinata.wanglin.database.ProvinceInfo;
import cn.sinata.wanglin.model.Village;
import cn.sinata.wanglin.neighbor.view.RxTextView;
import cn.sinata.wanglin.neighbor.view.SearchEditText;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class SearchVillageActivity extends BaseActivity {
    @BindView(R.id.mSwipeRefreshLayout)
    SwipeRefreshRecyclerLayout mSwipeRefreshLayout;
    @BindView(R.id.tv_search)
    SearchEditText tv_search;
    @BindView(R.id.tv_choice_city)
    TextView tv_choice_city;
    @BindView(R.id.tv_cancle)
    TextView tv_cancle;
    private ArrayList<Village> mVillages = new ArrayList<>();
    private VillageAdapter villageAdapter;
    String keyWord="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        tv_choice_city.setText(MyApplication.city);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_choice_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               showCity();
            }
        });
        initView();
    }

    private void showCity() {
        showDialog("加载中...");
        final ArrayList<ProvinceInfo> dataProvinceInfo=new ArrayList<>();
        final ArrayList<List<CityInfo>> dataCityInfo=new ArrayList<>();

        ProvinceDao mProvinceDao=new ProvinceDao(getApplicationContext());
        mProvinceDao.getAllProvinceInfoByDB(new JavaListBeanCallBack<ProvinceInfo>() {
            @Override
            public void onresult(int recode, List<ProvinceInfo> data, String message) {
                //选项1
                dataProvinceInfo.addAll(data);
            }
        });
        CityDao mCityDao=new CityDao(getApplicationContext());
        mCityDao.getAllCityInfoByDB2(new JavaListBeanCallBack<List<CityInfo>>() {
            @Override
            public void onresult(int recode, List<List<CityInfo>> data, String message) {
                dismissDialog();
                dataCityInfo.addAll(data);
                OptionsPickerView pvOptions= new OptionsPickerView(SearchVillageActivity.this);
                pvOptions.setPicker(dataProvinceInfo, dataCityInfo, true);
                pvOptions.setTitle("选择城市");
                //设置数据是否循环
                pvOptions.setCyclic(false);
                //监听确定选择按钮
                pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        tv_choice_city.setText(dataCityInfo.get(options1).get(option2).getCity_name());
                    }
                });
                pvOptions.show();
            }
        });
    }

    private void initView() {
        tv_search.setHint("请输入小区名称");
        villageAdapter = new VillageAdapter(mVillages);
        mSwipeRefreshLayout.setMode(SwipeRefreshRecyclerLayout.Mode.Top);
        mSwipeRefreshLayout.setLayoutManager(new LinearLayoutManager(mContext));
        mSwipeRefreshLayout.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .size(1)
                .color(ContextCompat.getColor(mContext, R.color.dividing_line_color))
                .build());
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshRecyclerLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }

            @Override
            public void onLoadMore() {

            }
        });
        mSwipeRefreshLayout.setAdapter(villageAdapter);
        villageAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                Village village = mVillages.get(position);
                MyApplication.houseid = village.getId();
                MyApplication.houseName = village.getHousingName();
                Intent mIntent=new Intent();
                mIntent.putExtra("housingId",village.getId());
                mIntent.putExtra("housingName",village.getHousingName());
                setResult(RESULT_OK,mIntent);
                finish();
            }
        });

        tv_search.setOnSearchActionListener(new SearchEditText.OnSearchActionListener() {
            @Override
            public void onSearch() {
                refresh();
            }
        });

        setTextChange();
    }
    private void refresh(){
        keyWord = tv_search.getText().toString();
        //重设文字触发change。
        tv_search.setText(keyWord);
        tv_search.setSelection(keyWord.length());
    }
    private void setTextChange(){
        RxTextView.textChanges(tv_search)
                .debounce(150, TimeUnit.MILLISECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .flatMap(new Func1<CharSequence, Observable<ResultData<ArrayList<Village>>>>() {
                    @Override
                    public Observable<ResultData<ArrayList<Village>>> call(CharSequence charSequence) {
                        keyWord = charSequence.toString();
                        if (TextUtils.isEmpty(charSequence)) {
                            return Observable.create(new Observable.OnSubscribe<ResultData<ArrayList<Village>>>() {
                                @Override
                                public void call(Subscriber<? super ResultData<ArrayList<Village>>> subscriber) {
                                    ResultData<ArrayList<Village>> resultData = new ResultData<>();
                                    resultData.setCode("SUCCESS");
                                    resultData.setMessage("关键字为空");
                                    resultData.setResultData(new ArrayList<Village>());
                                    subscriber.onCompleted();
                                    subscriber.onNext(resultData);
                                }
                            }).subscribeOn(Schedulers.io());
                        }
                        return HttpManager.searchHousing(tv_choice_city.getText().toString(),charSequence.toString());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultDataSubscriber<ArrayList<Village>>(this) {
                    @Override
                    public void onSuccess(String msg, ArrayList<Village> villages) {
                        mSwipeRefreshLayout.setRefreshing(false);
                        mVillages.clear();
                        if (villages.size() == 0) {
                            showToast("没有找到相关小区");
                        }
                        mVillages.addAll(villages);
                        villageAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mSwipeRefreshLayout.setRefreshing(false);
                        setTextChange();
                    }
                });
    }
}
